<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/4/22
 * Time: 11:34.
 */

namespace base;

/**
 * 微信驱动.
 *
 * @author  juzi
 *
 * @version 1.0.0
 * @date    2020年4月22日11:35:26
 */
class Wechat
{
    // appid
    private $_appid;

    // appsecret
    private $_appsecret;
    //回调url
    private $_ACCESS_TOKEN;

    /**
     * [__construct 构造方法].
     *
     * @author  juzi
     *
     * @version  1.0.0
     * @date    2020年4月22日11:35:26
     *
     * @param [string] $app_id     [应用appid]
     * @param [string] $app_secret [应用密钥]
     */
    public function __construct($app_id, $app_secret)
    {
        $this->_appid = $app_id;
        $this->_appsecret = $app_secret;

        //$this->_ACCESS_TOKEN   = $this->getToken();
    }

    /**
     * [getToken  获取全局token].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @date    2020年4月22日11:35:26
     *
     * @param [string] $appid      [应用appid]
     * @param [string] $app_secret [应用密钥]
     *
     * @return [string|boolean] [失败false, 成功返回tokenkey|]
     */
    public function getToken()
    {
        $tokenkey = config('property.cache_global_token').MyC('domain');
        //cache($tokenkey,null);

        if (cache($tokenkey)) {
            return cache($tokenkey);
        } else {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret;
            $ret = $this->HttpRequestGet($url);

            if ($ret['errcode']) {
                DataReturn([$ret['errmsg'], $ret['errcode']]);

                return false;
            }

            cache($tokenkey, $ret['access_token'], 7200);

            return $tokenkey;
        }
    }

    /**
     * [GetAuthCode 根据授权获取code].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @date    2020年4月22日11:35:26
     *
     * @param [string] $authcode [用户授权码]
     *
     * @return [string|boolean] [失败false, 成功返回appid|]
     */
    public function GetAuthCode()
    {
        // 请求获取code
        $redirect = __MY_PUBLIC_URL__.'api/index/wxlogin';
        $redirect = urlencode($redirect);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->_appid.'&redirect_uri='.$redirect.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        //跳转微信回调到redirect_uri获取code
//        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="
//            .$this->_appid."&redirect_uri=".$redirect."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        echo $url;
        exit;
        //header('Location: '.$url);
        //redirect($url);
    }

    /**
     * [GetWxAccessToken 根据授权code获取  access_token openid和session_key].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @date    2020年4月22日11:35:26
     *
     * @param [string] $authcode [用户授权码]
     *
     * @return [string|boolean] [失败false, 成功返回appid|]
     */
    public function GetAuthSessionKey($authcode)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->_appid.'&secret='.$this->_appsecret.'&code='.$authcode.'&grant_type=authorization_code';
        $ret = $this->HttpRequestGet($url);

        if (!$ret || isset($ret['errcode'])) {
            return DataReturn($ret['errmsg'], $ret['errcode']);
        }

        //$key = 'wechat_user_login_'.$ret['openid'];
        $key = config('property.cache_user_info').$ret['openid'];
        // 缓存存储
        cache($key, $ret);

        return $ret['openid'];
    }

    /**
     * [MiniQrCodeCreate 二维码创建].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @datetime 2018-01-02T19:53:10+0800
     *
     * @param [string] $params['page']  [页面地址]
     * @param [string] $params['scene'] [参数]
     *
     * @return [string] [成功返回文件流, 失败则空]
     */
    public function MiniQrCodeCreate($params)
    {
        // 请求参数
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'page',
                'error_msg' => 'page地址不能为空',
            ],
            [
                'checked_type' => 'length',
                'checked_data' => '1,32',
                'key_name' => 'scene',
                'error_msg' => 'scene参数 1~32 个字符之间',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if (true !== $ret) {
            return DataReturn($ret, -1);
        }

        // 获取access_token
        $access_token = $this->GetToken();
        if (false === $access_token) {
            return DataReturn('access_token获取失败', -1);
        }

        // 获取二维码
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $data = [
            'page' => $params['page'],
            'scene' => $params['scene'],
            'width' => empty($params['width']) ? 1000 : intval($params['width']),
        ];
        $res = $this->HttpRequestPost($url, json_encode($data), false);
        if (!empty($res)) {
            if (false === stripos($res, 'errcode')) {
                return DataReturn('获取成功', 0, $res);
            }
            $res = json_decode($res, true);
            $msg = isset($res['errmsg']) ? $res['errmsg'] : '获取二维码失败';
        } else {
            $msg = '获取二维码失败';
        }

        return DataReturn($msg, -1);
    }

    /**
     * [MiniMenuCreate 创建菜单].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @datetime2020年4月28日13:13:15
     *
     * @param [string] $params['page']  [页面地址]
     * @param [string] $params['scene'] [参数]
     *
     * @return [string] [成功返回文件流, 失败则空]
     */
    public function MenuCreate()
    {
        $json = '{
    "button": [
        {
            "type": "view",
            "name": "物业中心",
            "url": "http://property.utools.club/index.php/api/index/Index"
        }
    ]
}';
        // 获取access_token
        $access_token = $this->GetToken();
        if (false === $access_token) {
            return DataReturn('access_token获取失败', -1);
        }

        // 获取二维码
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $res = $this->HttpRequestPost($url, $json, false);
        if (!empty($res)) {
            if (false === stripos($res, 'errcode')) {
                return DataReturn('创建成功', 0, $res);
            }
            $res = json_decode($res, true);
            $msg = isset($res['errmsg']) ? $res['errmsg'] : '创建失败';
        } else {
            $msg = '创建失败';
        }

        return DataReturn($msg, -1);
    }

    /**
     * [GetUserInfo 关注后根据全局access_token获取 用户信息].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @date    2020年4月22日11:35:26
     *
     * @param [string] $access_token [全局access_token]
     * @param [string] $openid       [用户openid]
     *
     * @return [string|boolean] [失败false, 成功返回用户信息|]
     */
    public function GetUserInfo($openid)
    {
        $key = config('property.cache_user_info').$openid;

        $access_token = cache($key)['access_token'];

        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";

        $ret = $this->HttpRequestGet($url);
        // ($ret);exit;
        if (!$ret || isset($ret['errcode'])) {
            return false;
        }

        return $ret;
    }

    /**
     * [HttpRequestGet get请求].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @datetime 2018-01-03T19:21:38+0800
     *
     * @param [string] $url [url地址]
     *
     * @return [array] [返回数据]
     */
    private function HttpRequestGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return json_decode($res, true);
    }

    /**
     * [HttpRequestPost curl模拟post].
     *
     * @author   juzi
     *
     * @version  1.0.0
     * @datetime 2017-09-25T09:10:46+0800
     *
     * @param [string] $url        [请求地址]
     * @param [array]  $data       [发送的post数据]
     * @param [array]  $is_parsing [是否需要解析数据]
     *
     * @return [array] [返回的数据]
     */
    private function HttpRequestPost($url, $data, $is_parsing = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_POST, true);

        $res = curl_exec($curl);
        if (true === $is_parsing) {
            return json_decode($reponse, true);
        }

        return $res;
    }
}

?>

